package cn.fboost.mtos.task;

import cn.fboost.mtos.entity.Product;
import cn.fboost.mtos.mapper.ProductMapper;
import cn.fboost.mtos.mapper.ProductRateMapper;
import cn.fboost.mtos.mapper.ProductSaleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ProductTask {
    private final ProductMapper productMapper;
    private final ProductSaleMapper productSaleMapper;
    private final ProductRateMapper productRateMapper;

    public ProductTask(ProductMapper productMapper, ProductSaleMapper productSaleMapper, ProductRateMapper productRateMapper) {
        this.productMapper = productMapper;
        this.productSaleMapper = productSaleMapper;
        this.productRateMapper = productRateMapper;
    }

    /**
     * 累计商品销量
     *
     * @param productId 商品ID
     */
    @Async
    public void incrSales(int productId, int quantity) {
        productSaleMapper.incrSales(productId, quantity, new Date());
    }

    /**
     * 计算商品评分，2小时执行一次
     */
    @Scheduled(fixedRate = 1000 * 60 * 60 * 2)
    public void calcRating() {
        log.info("开始对商品评分进行计算");
        List<Integer> ids = productMapper.listIds();
        // 分别计算每一个商品的评分和总人数
        ids.forEach(id -> {
            List<Integer> rates = productRateMapper.listAllByProductId(id);
            int rateTotal = rates.size();
            double rate = rates.stream().mapToInt(Integer::intValue).average().orElse(0);

            Product product = new Product();
            product.setId(id);
            product.setRate(rate);
            product.setRateTotal(rateTotal);
            productMapper.update(product);
        });

        log.info("商品评分计算完成");
    }
}
